// 数据相关接口
var express = require('express');
var router = express.Router();
// 数据库相关配置和方法
const db = require('../utils/db/db');
const data_sql = require('../utils/db/sql/data');
const utils = require('../utils/utils');
router.get('/', function (req, res, next) {
    res.end()
});
router.post('/getAllData', function (req, res, next) {
    const token = req.header('accessToken') || '';
    let mustArr = [];
    let notMustArr = ['rangeDate', ];
    let numberArr = [];
    let params = utils.checkParams({
        data: req.body,
        mustArr,
        notMustArr,
        numberArr
    })
    if (params['msg']) {
        res.send({
            code: 400,
            msg: params['msg']
        })
        return
    }
    if (token) {
        utils.verifyToken(token).then((decoded) => {
            const username = decoded.username;
            if (params && params.rangeDate && params.rangeDate.length > 0) {
                params.rangeDate.forEach((item, index) => {
                    params.rangeDate[index] = utils.renderTime(item).split(' ')[0]
                })
                console.log(params.rangeDate, 'params.rangeDate')
                db.query(`${data_sql.selectDataDate}'${params.rangeDate[0]}' and '${params.rangeDate[1]}') and (username='${username}') ORDER BY date ASC`, (err, response) => {
                    if (err) res.send({
                        code: 400,
                        msg: db.DB_ERROR,
                    });
                    let response_result = JSON.parse(JSON.stringify(response)) || [];
                    console.log(response_result, 'response_result')
                    if (response_result && response_result.length > 0) {
                        response_result.forEach((item) => {
                            item['date'] = item['date'].split(' ')[0]
                        })
                    }
                    res.send({
                        code: 200,
                        data: response_result
                    });
                })
            } else {
                db.query(`${data_sql.selectData}'${username}' ORDER BY date ASC`, (err, response) => {
                    if (err) res.send({
                        code: 400,
                        msg: db.DB_ERROR,
                    });
                    let response_result = JSON.parse(JSON.stringify(response)) || [];
                    console.log(response_result, 'response_result')
                    if (response_result && response_result.length > 0) {
                        response_result.forEach((item) => {
                            item['date'] = item['date'].split(' ')[0]
                        })
                    }
                    res.send({
                        code: 200,
                        data: response_result
                    });
                })
            }
        })
    } else {
        res.send({
            code: 400,
            msg: 'token丢失,请重新登录'
        });
    }

})
// 根据date查询数据
router.post('/getDateByDate', function (req, res, next) {
    const token = req.header('accessToken') || '';
    let mustArr = [];
    let notMustArr = ['date', ];
    let numberArr = [];
    let params = utils.checkParams({
        data: req.body,
        mustArr,
        notMustArr,
        numberArr
    })
    if (params['msg']) {
        res.send({
            code: 400,
            msg: params['msg']
        })
        return
    }
    if (token) {
        utils.verifyToken(token).then((decoded) => {
            const username = decoded.username;
            if (params && params.date) {
                params.date= utils.renderTime(params.date).split(' ')[0]
                db.query(`${data_sql.selectDataDate}'${params.date}' and '${params.date}') and (username='${username}') ORDER BY date ASC`, (err, response) => {
                    if (err) res.send({
                        code: 400,
                        msg: db.DB_ERROR,
                    });
                    let response_result = JSON.parse(JSON.stringify(response)) || [];
                    if (response_result && response_result.length > 0) {
                        response_result.forEach((item) => {
                            item['date'] = item['date'].split(' ')[0]
                        })
                    }
                    res.send({
                        code: 200,
                        data: response_result
                    });
                })
            }
        })
    } else {
        res.send({
            code: 400,
            msg: 'token丢失,请重新登录'
        });
    }

})
router.post('/addData', (req, res) => {
    const token = req.header('accessToken') || '';
    let mustArr = ['date'];
    let notMustArr = ['stock', 'fund', 'gold'];
    let numberArr = [];
    let params = utils.checkParams({
        data: req.body,
        mustArr,
        notMustArr,
        numberArr
    })
    if (params['msg']) {
        res.send({
            code: 400,
            msg: params['msg']
        })
        return
    }
    if (token) {
        utils.verifyToken(token).then((decoded) => {
            const username = decoded.username;
            let dataArr = [params.date, params.stock || 0, params.fund || 0, params.gold || 0, username]
            db.query(`${data_sql.addData}`, dataArr, (err, response) => {
                if (err) {
                    res.send({
                        code: 400,
                        msg: db.DB_ERROR,
                    });
                } else {
                    res.send({
                        code: 200,
                        msg: '新增成功'
                    });
                }

            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: err
            });
            console.log(err)
        })
    } else {
        res.send({
            code: 400,
            msg: 'token丢失,请重新登录'
        });
    }
});
router.post('/updateData', (req, res) => {
    const token = req.header('accessToken') || '';
    let mustArr = ['date','dataId'];
    let notMustArr = ['stock', 'fund', 'gold'];
    let numberArr = ['dataId'];
    let params = utils.checkParams({
        data: req.body,
        mustArr,
        notMustArr,
        numberArr
    })
    if (params['msg']) {
        res.send({
            code: 400,
            msg: params['msg']
        })
        return
    }
    if (token) {
        utils.verifyToken(token).then((decoded) => {
            const username = decoded.username;
            db.query(`update data set stock=${params['stock']},fund=${params['fund']},gold=${params['gold']} WHERE dataId=${params['dataId']}`, (err, response) => {
                if (err) {
                    res.send({
                        code: 400,
                        msg: db.DB_ERROR,
                    });
                } else {
                    res.send({
                        code: 200,
                        msg: '操作成功'
                    });
                }

            })
        }).catch(err => {
            res.send({
                code: 400,
                msg: err
            });
            console.log(err)
        })
    } else {
        res.send({
            code: 400,
            msg: 'token丢失,请重新登录'
        });
    }
});
module.exports = router;